package com.wjwframework.jfinal.handler;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.handler.Handler;
import com.wjw.utils.IP;
import com.wjwframework.jfinal.web.utils.WebUtils;

/**
 * @author wjw
 * @time 2015年12月30日下午2:29:31
 */
public class RequestHandler extends Handler {

	private Logger log=LoggerFactory.getLogger(getClass());
	
	@Override
	public void handle(String target, HttpServletRequest request,HttpServletResponse response, boolean[] isHandled) {
		if (target.endsWith(".do"))
	        target = target.substring(0, target.length() - 3);
		if(target.contains(".do;JSESSIONID="))
			target = target.replace(".do;JSESSIONID=",";JSESSIONID=");
		
		String ip=IP.getRemoteAddr(request);//ip
		Integer port=request.getRemotePort();//端口号
		String uri=request.getRequestURI();//请求uri地址
		String requestType=request.getContentType();//request请求类型
		String parameter="";//请求参数
		
		StringBuilder sb = new StringBuilder("------------------------------------------begin------------------------------------------\n");
		long start=System.currentTimeMillis();
		isHandled[0]=true;
		sb.append(ip+"\t"+port+"\n");
		sb.append(uri+"\trequestType:"+requestType+"\n");
		
		// Invocationprint all parameters
		Enumeration<String> e = request.getParameterNames();
		if (e.hasMoreElements()) {
			sb.append("Parameter\t");
			while (e.hasMoreElements()) {
				String name = e.nextElement();
				String[] values = request.getParameterValues(name);
				if (values.length == 1) {
					parameter+=name+"="+values[0];
				}
				else {
					sb.append(name).append("[]={");
					for (int i=0; i<values.length; i++) {
						if (i > 0)
							parameter+=",";
						parameter+=values[i];
					}
					parameter+="}";
				}
				parameter+="  ";
			}
			parameter+="\n";
		}
		sb.append(parameter);
		next.handle(target, request, response, isHandled);
		sb.append("responseType\t"+response.getContentType()+"\n");
		String responseType=response.getContentType();
		long end=System.currentTimeMillis();
		sb.append("-------------------------------------------end共用时"+(end-start)+"ms---------------------------------------\r\n\r\n");
		//日志进log文件
//		log.info("\n"+sb);
		
//		------------------------------------------begin------------------------------------------
//		192.168.0.48	64542
//		/wb/api/topic/findList.do	contentType:application/x-www-form-urlencoded;charset=utf-8
//		Parameter	sign=5ac9488e464fe225925214494932ff18  u_id=AEE0BB07C76C415EB0C9697E65891854  page=1  u_token=1BA450A907BD4582BAFC2A29063BB44D  
//		response-type	application/json;charset=UTF-8
//		-------------------------------------------end共用时14ms---------------------------------------
/*		
		//日志进mongodb
		Record re = new Record()
		.set("ip",ip)
		.set("port", port)
		.set("uri", uri)
		.set("parameter", getParamMap(request))//将map参数对象写入mongodb
		.set("request_type", requestType)
		.set("response_type", responseType)
		.set("time_sum", (end-start)+"ms")
		.set("ctime", new Date());
		//添加访问记录到mongodb中
		MongoKit.save("access", re);*/
		
		//将request存储到webUtils中
		WebUtils.remove();
		WebUtils.set(request);
	}
	
	/**
	 * 获取参数的集合
	 * @param request
	 * @return 参数的集合
	 */
	private Map<String, Object> getParamMap(HttpServletRequest request) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Enumeration<String> paramNames = request.getParameterNames();
		String paramName = "";
		String paramValue = "";
		while (paramNames.hasMoreElements()) {
			paramName = paramNames.nextElement();
			paramValue = request.getParameter(paramName);
			//如果参数名带“.”则替换为下划线“_”
			paramName=paramName.replace(".", "_");
			paramMap.put(paramName, paramValue);
		}
		return paramMap;
	}
}